import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { environment } from "../../../../../../environments/environment";
import * as _ from "lodash";
import { ApplyFundGroupComponent } from '../apply-fund-group/apply-fund-group.component';
import { EntryChangeService } from './entry-change.service';
import { CommitComponent } from '../commit/commit.component';
import { DataService } from '../../../../../services/data.service';
import { Util } from '../../../../../common/util';
import { SelectItem } from 'primeng/components/common/api';
@Component({
  selector: 'app-entry-change',
  templateUrl: './entry-change.component.html',
  styleUrls: ['./entry-change.component.scss'],
  providers: [EntryChangeService]
})
export class EntryChangeComponent implements OnInit {
  // 保存并提交modal
  @ViewChild("entryCommitModal", { read: ViewContainerRef })
  entryCommitModal: ViewContainerRef;
  commitComponent: ComponentRef<CommitComponent>;
  // 适用基金组modal
  @ViewChild("applyFundGroup", { read: ViewContainerRef })
  applyFundGroup: ViewContainerRef;
  applyFundGroupComponent: ComponentRef<ApplyFundGroupComponent>;
  //字典值列表
  public dictionaryList: any = {
    RISK_RECORD_TYPE: [],//属性
    NX_SOURCE: [],//条款出处
    RISK_ACCOUNT_TYPE: [],//适用基金组类别
    RISK_CTRL_METHOD: [],//事中控制方法
    RISK_CONTROL_AFTER: [],//事后监控方法
    MONITOR_REMARK: [],//风险等级
    RISK_CW_CTRL: [],//是否场外系统可控
    RISK_HS_CONTROL: []//是否事中系统可控
  }
  public dictionaryInfo: SelectItem[];
  //全选按钮
  public isCheckedAll: any = false;
  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //条目修改下拉框绑定数据
  public dataInfo: any = {
    sVaild: '',//是否有效
    sItemType: '',//属性
    sFileSource: '',//条款出处
    sFileName: '',//文件名称
    sFundType: '',//适用基金组类型
    sFundGroupdsZh: '',//适用基金组
    sFundGroupds: '',
    f1: ''//内容
  }
  ////从分页列表获取到的数据条目修改列表
  public list: any = [];
  //从分页列表获取到的数据条目修改克隆列表
  public listData: any = [];
  //用于判断数据是否改变的克隆列表
  public listDataClone: any = [];
  constructor(
    public dataService: DataService,
    public resolver: ComponentFactoryResolver,
    public entryChangeService: EntryChangeService
  ) {

  }


  //在指定位置新增一行
  addRow() {
    let checkedList: any = [];
    let indexList: any = [];
    _.forEach(this.listData, (item, index) => {
      indexList.push(index)
      if (item.isChecked) {
        checkedList.push(index);
      }
    })
    if (checkedList.length == 1) {
      let body: any = {
        nNdId: "",
        nSortNo: "",
        sState: "",
        nBatchNo: "",
        sValid: "",
        sItemType: "",
        sFileName: "",
        sFileSource: "",
        sFundGroupds: "",
        sFundGroupdsZh: "",
        sFundType: [],
        sState2: "",
        sBatchNo2: "",
        f1: "",
        f2: "",
        f3: "",
        f4: "",
        f5: "",
        f6: "",
        f7: "",
        f8: "",
        f9: "",
        f10: "",
        f11: "",
        f12: "",
        f13: "",
        f14: "",
        f15: "",
        f16: "",
        f17: "",
        f18: "",
        f19: "",
        f20: ""
      }
      var sortedIndex = _.sortedIndex(indexList, checkedList[0]);
      this.listData.splice(sortedIndex + 1, 0, body);
      console.log(sortedIndex)
      console.log(checkedList[0])
      console.log(indexList)
      console.log(this.listData)
      // Util.loadSelect(this.dictionaryList.RISK_ACCOUNT_TYPE, 'selectpicker' + sortedIndex + 1)
      // window['$']('#selectpicker' + sortedIndex + 1).selectpicker('render');

    } else {
      window['swal']("提示", "请选择一条数据", "warning")
    }

  }
  //删除指定行
  delRow() {
    let that = this;
    // this.listData = _.filter(this.listData, (item: any) => {
    //   return item.isChecked == false || item.isChecked == undefined;
    // })
    window['swal'](
      {
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        showLoaderOnConfirm: true,
        title: "提示",
        text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否删除选中行" + "</div>",
        html: true
      }, function () {
        that.listData = _.filter(that.listData, (item: any) => {
          return item.isChecked == false || item.isChecked == undefined;
        })
      }
    );
  }
  //修改勾选的条目
  changeCheckedInfo(field) {
    let that = this;
    _.forEach(this.listData, (item, index) => {
      if (item.isChecked) {
        switch (field) {
          case 'sItemType':
            // let value1 = that.getValueByKey(that.dataInfo.sItemType, 'RISK_RECORD_TYPE')
            item.sItemType = that.dataInfo.sItemType;
            that.inputChange(index, item.sItemType, field, 'RISK_RECORD_TYPE')
            break;
          case 'sFileSource':
            // let value2 = that.getValueByKey(that.dataInfo.sFileSource, 'NX_SOURCE')
            item.sFileSource = that.dataInfo.sFileSource;
            that.inputChange(index, item.sFileSource, field, 'NX_SOURCE')
            break;
          case 'sFileName':
            item.sFileName = that.dataInfo.sFileName;
            that.inputChange(index, item.sFileName, field)
            break;
          case 'sFundType':
            // let value3 = that.getValueByKey(that.dataInfo.sFundType, 'RISK_ACCOUNT_TYPE')
            window['$']('#NqdiiEntryChangeFundType' + index).selectpicker('val', that.dataInfo.sFundType);
            console.log("运行了")
            console.log('#NqdiiEntryChangeFundType' + index)
            console.log(that.dataInfo.sFundType)
            that.inputChange(index, item.sFundType, field)
            item.sFundType = that.dataInfo.sFundType;
            break;
          case 'sFundGroupdsZh':
            item.sFundGroupdsZh = that.dataInfo.sFundGroupdsZh;
            item.sFundGroupds = that.dataInfo.sFundGroupds;
            that.inputChange(index, item.sFundGroupdsZh, field)
            break;
          case 'f1':
            item.f1 = that.dataInfo.f1;
            that.inputChange(index, item.f1, field)
            break;
          case 'sValid':
            item.sValid = that.dataInfo.sValid;
            that.inputChange(index, item.sValid, field)
            break;
        }
      }
    })
  }
  ngOnInit() {
    let that = this;
    this.listData = _.cloneDeep(this.list);
    this.listDataClone = _.cloneDeep(this.list);
    // 初始化日期控件
    flatpickr.localize(zh);
    // 多选下拉框
    window['$'](".select2").select2();
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    Util.loadSelect(this.dictionaryList.RISK_ACCOUNT_TYPE, 'NqdiiEntryChangeFundType');
    _.forEach(this.listData, it => {
      if (it.sFundType != null) {
        it.sFundType = it.sFundType.split(",");
      }
    })
    this.dictionaryInfo = Util.loadPrimeSelect(this.dictionaryList.RISK_ACCOUNT_TYPE);
    this.dataService.nQDIIInputModelEmitter = new EventEmitter();
    this.dataService.nQDIIInputModelEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'inputModel':
            that.dataInfo.sFundGroupdsZh = that.dataService.nQDIIFGroupInfo;
            that.dataInfo.sFundGroupds = that.dataService.nQDIIIdList;
            that.changeCheckedInfo('sFundGroupdsZh')
            window['$']('#applyFundGroup').modal('hide');
            break;
          case 'index':
            that.listData[that.dataService.nQDIIIndexId].sFundGroupdsZh = that.dataService.nQDIIFGroupInfo;
            that.listData[that.dataService.nQDIIIndexId].sFundGroupds = that.dataService.nQDIIIdList;
            window['$']('#applyFundGroup').modal('hide');
            break;
        }
      }
    })
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      // this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    // this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  //适用基金组modal
  showApplyFundGroup(index?) {
    // 判断组件是否已创建，如果创建先注销
    if (this.applyFundGroupComponent && this.applyFundGroupComponent.instance) {
      this.applyFundGroupComponent.destroy();
    }
    // 动态创建组件的实例
    const applyFundGroupComponent = this.resolver.resolveComponentFactory(ApplyFundGroupComponent);
    this.applyFundGroupComponent = this.applyFundGroup.createComponent(applyFundGroupComponent);
    if (index != null) {
      this.applyFundGroupComponent.instance.index = index;
      if (this.listData[index].sFundGroupdsZh != '' && this.listData[index].sFundGroupdsZh != null && this.listData[index].sFundGroupdsZh != undefined) {
        this.applyFundGroupComponent.instance.checkedIdList = this.listData[index].sFundGroupds.split(',');
        console.log(this.listData[index].sFundGroupds.split(','))
      }
    } else {
      this.applyFundGroupComponent.instance.modeType = 'input';
      if (this.dataInfo.sFundGroupdsZh != '' && this.dataInfo.sFundGroupdsZh != null && this.dataInfo.sFundGroupdsZh != undefined) {
        this.applyFundGroupComponent.instance.checkedIdList = this.dataInfo.sFundGroupds.split(',');
        console.log(this.dataInfo.sFundGroupds.split(','))
      }

    }
    window['$']('#applyFundGroup').modal('show');
  }
  //批量录入-录入信息(保存按钮)
  save() {
    let that = this;
    let postBody: any = [];
    //用于校验是否数据是否已修改
    let dataList: any = [];
    let listData: any = _.cloneDeep(this.listData);
    if (this.proofInfo()) {
      _.forEach(listData, item => {
        let isNull: any = true;
        if (item.isChecked) {
          dataList.push(item);
          delete item.isChecked;
          _.forIn(item, (value, key) => {
            if (value != '' && value != null) {
              isNull = false;
            }
          })
          if (!isNull) {
            //判断选中的对象的sFundType是否为数组
            if (Array.isArray(item.sFundType)) {
              item.sFundType = item.sFundType.join(',');
            }
            postBody.push(item)
          }

        }
      })
     
      if (postBody.length == 0) {
        window['swal']("提示", "请选择一条或者多条不为空的数据", "warning")
      } else {
        let list: any = [];
        _.forEach(dataList, item => {
          let item2 = _.filter(that.list, (it: any) => { return item.nNdId == it.nNdId })[0];
          if (Util.objectCheck(item, item2)
          ) {
            list.push(item.nNdId);
          } else {
            let list = that.contrastField(item, item2)
            _.forEach(postBody, it => {
              if (it.nNdId == item.nNdId) {
                it['changeField'] = list;
              }
            })
          }
        })
        if (list.length > 0) {
          let listItem = list.join(',')
          window['swal']("提示", "编号为" + listItem + '的数据没有修改', "warning")
        } else {
          console.log(JSON.stringify(postBody))
          window['swal']({
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            showLoaderOnConfirm: true,
            title: "提示",
            text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否录入选中的信息" + "</div>",
            html: true
          },
            function (isConfirm) {
              if (isConfirm) {
                that.entryChangeService.save(postBody).subscribe(data => {
                  if (data) {
                    window['swal']("提示", "录入信息成功", "success")
                    console.log("到了")
                    that.dataService.nQDIIsEntryChangeEmitter.emit('entryChangeSave');
                    console.log("发射了？")
                  }
                })
              }
            })
        }

      }
    }
  }
  //校验录入模式保存或者保存并提交时必填的6个字段
  proofInfo() {
    let allInfoList: any = [];
    _.forEach(this.listData, (item, index) => {
      let checkInfo: any = [];
      let checkItem: any;
      if (item.isChecked) {
        if (item.sFileSource == null || item.sFileSource == '') {
          checkInfo.push('条款出处')
        }
        if (item.sFundType == null || item.sFundType == '') {
          checkInfo.push('适用基金类别')
        }
        if (item.sItemType == null || item.sItemType == '') {
          checkInfo.push('属性')
        }
        if (item.sFileName == null || item.sFileName == '') {
          checkInfo.push('文件名称')
        }
        if (item.f1 == null || item.f1 == '') {
          checkInfo.push('内容')
        }
        if (item.sFundGroupdsZh == null || item.sFundGroupdsZh == '') {
          checkInfo.push('适用基金组')
        }
        if (checkInfo.length > 0) {
          checkItem = checkInfo.join('、');
          let math = index + 1;
          allInfoList.push('序号为' + math + '的数据' + checkItem + '字段不能为空</br>')

        }

      }
    })
    if (allInfoList.length > 0) {
      window['swal'](
        {
          type: "warning",
          confirmButtonText: "确认",
          closeOnConfirm: true,
          title: "提示",
          text: "<div style='max-height: 200px;overflow-y: auto;'>" + allInfoList.join(' ') + "</div>",
          html: true
        }, function () {

        }
      );
      return false;
    } else {
      return true;
    }
  }
  //对比两个对象中哪些数据不同，返回数据不相同的数据的key值
  contrastField(data1: any, data2: any) {
    let list: any = [];
    _.forIn(data1, (value, key) => {
      if (value == data2[key]) {

      } else {
        list.push(key);
      }
    })
    return list;
  }

  //批量录入提交-保存提交(保存并提交按钮)
  submit() {
    let that = this;
    let postBody: any = [];
    //用于校验是否数据是否已修改
    let dataList: any = [];
    let listData: any = _.cloneDeep(this.listData);
    if (this.proofInfo()) {
      _.forEach(listData, item => {
        let isNull: any = true;
        if (item.isChecked) {
          dataList.push(item);
          delete item.isChecked;
          _.forIn(item, (value, key) => {
            if (value != '' && value != null) {
              isNull = false;
            }
          })
          if (!isNull) {
            //判断选中的对象的sFundType是否为数组
            if (Array.isArray(item.sFundType)) {
              item.sFundType = item.sFundType.join(',');
            }
            postBody.push(item)
          }
        }
      })
      if (postBody.length == 0) {
        window['swal']("提示", "请选择一条或者多条不为空的数据", "warning")
      } else {
        let list: any = [];
        _.forEach(dataList, item => {
          
          let item2 = _.filter(that.list, (it: any) => { return item.nNdId == it.nNdId })[0];
          if (Util.objectCheck(item, item2)
          ) {
            list.push(item.nNdId);
          } else {
            let list = that.contrastField(item, item2)
            _.forEach(postBody, it => {
              if (it.nNdId == item.nNdId) {
                it['changeField'] = list;
              }
            })
          }
        })
        if (list.length > 0) {
          let listItem = list.join(',')
          window['swal']("提示", "编号为" + listItem + '的数据没有修改', "warning")
        } else {
          console.log(JSON.stringify(postBody))
          that.showCommitModal(postBody);
        }


      }
    }
  }
  //保存并提交modal
  showCommitModal(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.commitComponent && this.commitComponent.instance) {
      this.commitComponent.destroy();
    }
    // 动态创建组件的实例
    const commitComponent = this.resolver.resolveComponentFactory(CommitComponent);
    this.commitComponent = this.entryCommitModal.createComponent(commitComponent);
    this.commitComponent.instance.InputpostBody = item;
    this.commitComponent.instance.commitType = '条目修改';
    window['$']('#entryCommitModal').modal('show');
  }
  //根据字典key查询value
  getValueByKey(key, dictionaryName) {
    let that = this;
    let info: any;
    switch (dictionaryName) {
      case 'RISK_RECORD_TYPE':
        info = _.filter(that.dictionaryList.RISK_RECORD_TYPE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'NX_SOURCE':
        info = _.filter(that.dictionaryList.NX_SOURCE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_ACCOUNT_TYPE':
        info = _.filter(that.dictionaryList.RISK_ACCOUNT_TYPE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CTRL_METHOD':
        info = _.filter(that.dictionaryList.RISK_CTRL_METHOD, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CONTROL_AFTER':
        info = _.filter(that.dictionaryList.RISK_CONTROL_AFTER, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'MONITOR_REMARK':
        info = _.filter(that.dictionaryList.MONITOR_REMARK, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CW_CTRL':
        info = _.filter(that.dictionaryList.RISK_CW_CTRL, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_HS_CONTROL':
        info = _.filter(that.dictionaryList.RISK_HS_CONTROL, (item: any) => {
          return item.sItemKey == key
        })
        break;
    }
    // console.log("纳尼？？")
    // console.log(info[0])
    return info[0].sItemValue;
  }
  //根据参数判断需要转义的字段
  translateByName(i: any, name: any, itemCode: any) {
    let that = this;
    let nameZh = name + 'Zh';
    if (that.listData[i][name] != '' && that.listData[i][name] != null && that.listData[i][name] != undefined) {
      this.listData[i][nameZh] = this.getValueByKey(that.listData[i][name], itemCode)
    } else {
      this.listData[i][nameZh] = '';
    }
  }
  // 修改标蓝(i为下标,value为修改后的值,name为字段名)
  inputChange(i: any, value: any, name: any, itemCode?) {
    let that = this;
    //转义
    if (itemCode != undefined) {
      this.translateByName(i, name, itemCode);
    }
    // 定位tr
    let index = i + 1;
    // 定位输入框和选择框
    let id = "#input-table tbody tr:nth-child(" + index + ") td div[id=" + name + "]";
    // let id2 = "#input-table tbody tr:nth-child(" + index + ") td select[name=" + name + "]";
    // 获取当前修改对象
    let item = this.listDataClone[i];
    // 循环对象
    for (let key in item) {
      // 判断字段名是否相等
      if (key == name) {
        // 判断原值是否为null(后端空值返回null,前端空值为'',实际都为空,相等)
        if (item[key] == null) {
          if (value == '') {
            window['$'](id).removeClass('triangle-topleft');
          } else {
            window['$'](id).addClass('triangle-topleft');
          }
        } else {
          // 判断原值不为null,直接对比
          if (item[key] == value) {
            console.log("触发1")
            window['$'](id).removeClass('triangle-topleft');
          } else {
            console.log("触发2")
            window['$'](id).addClass('triangle-topleft');
          }
        }
      }
    }
  }
}
